import Vue from "vue";
import VueRouter from "vue-router";
//使用路由插件
Vue.use(VueRouter);
/* 
  为什么要重写push,因为push方法返回promise实例,但是如果我们不传递第三个参数onAbort,则push内部的catch函数没有处理异常的回调函数,所以如果push出错,就会直接抛出错误到浏览器上
*/

//重写路由push方法
const lastPush = VueRouter.prototype.push;
/*
push在VueRouter的原型上放,直接修改为新的函数并传递三个参数,传入的onComplate和onAbort参数的默认参数为一个函数 这样当有报错的时候 catch就会有回调函数进行处理(关键)
*/
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  /* 
    因为之前的push在VueRouter的原型对象上放,所以原本的push中this就是指向VueRouter的实例
    但是现在lastPush被直接默认调用,所以this就指向了undefined了,内部很可能出错
    我们在调用lastPush的时候,可以改变他的this指向VueRouter的实例
  */
  return lastPush.call(this, location, onComplete, onAbort);
};

//引入路由组件(懒加载)
const Home = () => import("@pages/Home/Home.vue");
const Login = () => import("@pages/Login/Login.vue");
const Search = () => import("@pages/Search/Search.vue");
const Register = () => import("@pages/Register/Register.vue");

export default new VueRouter({
  mode: "history",
  routes: [
    // 默认路由
    {
      path: "/",
      redirect: "/home",
    },
    {
      path: "/home",
      component: Home,
      name: "home",
    },
    {
      path: "/search/:keyword?",
      component: Search,
      name: "search",
    },
    {
      path: "/login",
      component: Login,
      name: "login",
      meta: {
        FooterIsHidden: true,
      },
    },
    {
      path: "/register",
      component: Register,
      name: "register",
      meta: {
        FooterIsHidden: true,
      },
    },
  ],
});
